package com.itheima.service.system.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.system.DeptDao;
import com.itheima.domain.system.Dept;
import com.itheima.factory.MapperFactory;
import com.itheima.service.system.DeptService;
import com.itheima.utils.UUIDUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class DeptServiceImpl implements DeptService {
    @Override
    public PageInfo<Dept> queryPage(Integer pageNum, Integer pageSize) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = sqlSession.getMapper(DeptDao.class);
        PageHelper.startPage(pageNum, pageSize);
        List<Dept> list = mapper.findAll();
        PageInfo<Dept> pageInfo = new PageInfo<>(list);
        sqlSession.close();
        return pageInfo;
    }

    @Override
    public List<Dept> findAll() throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = sqlSession.getMapper(DeptDao.class);
        List<Dept> list = mapper.findAll();
        sqlSession.close();
        return list;
    }

    @Override
    public Dept findById(String id) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = sqlSession.getMapper(DeptDao.class);
        Dept dept = mapper.findById(id);
        sqlSession.close();
        return dept;
    }

    @Override
    public void save(Dept dept) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = sqlSession.getMapper(DeptDao.class);
        dept.setId(UUIDUtil.getSimpleUUID());
        mapper.save(dept);
        sqlSession.commit();
        sqlSession.close();

    }

    @Override
    public void deleteById(String... ids) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = sqlSession.getMapper(DeptDao.class);
        for (String id : ids) {
            mapper.deleteById(id);
        }
        sqlSession.commit();
        sqlSession.close();

    }

    @Override
    public void update(Dept dept) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        DeptDao mapper = sqlSession.getMapper(DeptDao.class);
        mapper.update(dept);
        sqlSession.commit();
        sqlSession.close();
    }
}
